<?php

namespace App\Kuafu\Export\Service\ExportFactory;

use App\Kuafu\Common\Service\ImageGenerationService;
use Illuminate\Support\Str;
use setasign\Fpdi\Fpdi;

/**
 * app-价签下载
 */
class ExportPriceTagService extends BaseExportService
{
    private string $localPath = '';

    public function query(): self
    {
        ini_set('memory_limit','1024M');

        $goods = $this->params['otherParams']['goods'] ?? [];
        $filePathArr = [];
        foreach ($goods as $goodsItem) {
            $filePathArr[] = ImageGenerationService::generatePriceTag($goodsItem['name'], $goodsItem['price']);
        }

        $rootPath = sys_get_temp_dir() . '/priceTagPdfFile';
        if (!is_dir($rootPath)) {
            mkdir($rootPath, 0777, true);
        }
        $this->localPath = $rootPath . '/' . Str::random(10) . '.pdf';

        // 生成PDF
        if (count($filePathArr)) {
            $pdf = new Fpdi('L', 'pt');

            $pdf->AddPage('L', [1276, 402]);
            $pdf->Image(ImageGenerationService::getFile('firstInstruction.png'), 0, 0, 1276);

            foreach ($filePathArr as $item) {
                $pdf->AddPage('L', [1276, 402]);
                $pdf->Image($item, 0, 0, 1276);
            }

            // 输出PDF文件
            $pdf->Output('F', $this->localPath);

            foreach ($filePathArr as $item) {
                @unlink($item);
            }
        }

        return $this;
    }

    public function path(): string
    {
        $oss = $this->upload($this->localPath);
        @unlink($this->localPath);
        return $oss;
    }
}
